#import "CascadePickerView.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kPickerHeight 250
#define kToolbarHeight 44

@interface CascadePickerView ()

@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UIBarButtonItem *cancelButton;
@property (nonatomic, strong) UIBarButtonItem *confirmButton;
@property (nonatomic, strong) UIBarButtonItem *titleLabel;
@property (nonatomic, assign) BOOL isLoading;

@end

@implementation CascadePickerView

#pragma mark - 初始化方法

- (instancetype)initWithLeftData:(NSArray *)leftData {
    return [self initWithLeftData:leftData columns:2];
}

- (instancetype)initWithLeftData:(NSArray *)leftData columns:(NSInteger)columns {
    self = [super initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    if (self) {
        self.leftData = leftData;
        self.rightDataCache = [NSMutableDictionary dictionary];
        self.selectedLeftIndex = 0;
        self.selectedRightIndex = 0;
        self.isLoading = NO;
        self.columns = MAX(1, columns); // 至少一列
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    // 背景遮罩
    self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
    self.backgroundView.backgroundColor = [UIColor blackColor];
    self.backgroundView.alpha = 0;
    [self addSubview:self.backgroundView];
    
    // 点击背景隐藏
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [self.backgroundView addGestureRecognizer:tapGesture];
    
    // 容器视图
    self.containerView = [[UIView alloc] init];
    self.containerView.backgroundColor = [UIColor whiteColor];
    self.containerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kPickerHeight + kToolbarHeight);
    [self addSubview:self.containerView];
    
    // 工具栏
    self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kToolbarHeight)];
    self.toolbar.barStyle = UIBarStyleDefault;
    [self.containerView addSubview:self.toolbar];
    
    // 取消按钮
    self.cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonClicked)];
    
    // 确认按钮
    self.confirmButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(confirmButtonClicked)];
    
    // 标题
    self.titleLabel = [[UIBarButtonItem alloc] initWithTitle:@"级联选择器" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.titleLabel.enabled = NO;
    
    // 设置工具栏按钮
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [self.toolbar setItems:@[flexibleSpace,self.cancelButton, flexibleSpace,flexibleSpace,flexibleSpace, self.titleLabel, flexibleSpace,flexibleSpace,flexibleSpace, self.confirmButton,flexibleSpace] animated:NO];
    
    // PickerView
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kToolbarHeight, kScreenWidth, kPickerHeight)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.containerView addSubview:self.pickerView];
    
    // 预加载第一个左侧选项的右侧数据
    // 注意：现在不自动加载，由外部控制
}

#pragma mark - 显示和隐藏方法

- (void)show {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0.4;
        CGRect frame = self.containerView.frame;
        frame.origin.y = kScreenHeight - frame.size.height;
        self.containerView.frame = frame;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0;
        CGRect frame = self.containerView.frame;
        frame.origin.y = kScreenHeight;
        self.containerView.frame = frame;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - 按钮点击事件

- (void)cancelButtonClicked {
    [self dismiss];
    
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
    if ([self.delegate respondsToSelector:@selector(cascadePickerViewDidCancel:)]) {
        [self.delegate cascadePickerViewDidCancel:self];
    }
}

- (void)confirmButtonClicked {
    [self dismiss];
    
    if(self.leftData.count == 0) return;
    
    NSString *leftValue = self.leftData[self.selectedLeftIndex];
    NSArray *rightData = self.rightDataCache[leftValue];
    NSString *rightValue = rightData ? rightData[self.selectedRightIndex] : @"";
    
    if (self.completionBlock) {
        self.completionBlock(leftValue, rightValue);
    }
    
    if (self.completionIndexBlock) {
        self.completionIndexBlock(self.selectedLeftIndex, self.selectedRightIndex);
    }
    
    if ([self.delegate respondsToSelector:@selector(cascadePickerView:didSelectLeftValue:rightValue:)]) {
        [self.delegate cascadePickerView:self didSelectLeftValue:leftValue rightValue:rightValue];
    }
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return self.columns;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.leftData.count;
    } else if (component == 1 && self.columns > 1) {
        if(self.selectedLeftIndex < self.leftData.count) {
            NSString *selectedLeftValue = self.leftData[self.selectedLeftIndex];
            NSArray *rightData = self.rightDataCache[selectedLeftValue];
            
            // 如果没有缓存数据，显示一行"加载中..."
            return rightData ? rightData.count : 1;
        }
        
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate

// 移除原有的 attributedTitleForRow 方法，替换为：
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = (UILabel *)view;
    if (!label) {
        label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:16.0]; // 设置字体大小
        label.textColor = main_text_color; // 设置文字颜色
        label.adjustsFontSizeToFitWidth = YES;
        label.minimumScaleFactor = 0.8;
    }
    
    NSString *title = @"";
    if (component == 0) {
        title = self.leftData[row];
    } else if (component == 1 && self.columns > 1) {
        NSString *selectedLeftValue = self.leftData[self.selectedLeftIndex];
        NSArray *rightData = self.rightDataCache[selectedLeftValue];
        
        if (rightData) {
            title = rightData[row];
        } else {
            title = @"加载中...";
        }
    }
    
    label.text = title;
    return label;
}

// 必须实现行高方法
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 44.0; // 根据字体大小调整行高
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        // 左侧选择变化，触发加载右侧数据
        self.selectedLeftIndex = row;
        self.selectedRightIndex = 0; // 重置右侧选择
        
        // 刷新右侧列
        if (self.columns > 1) {
            [self.pickerView reloadComponent:1];
            
            // 触发数据加载回调
            NSString *leftValue = self.leftData[row];
            [self requestRightDataForLeftValue:leftValue];
        }
    } else if (component == 1) {
        self.selectedRightIndex = row;
    }
}

#pragma mark - 数据加载

- (void)requestRightDataForLeftValue:(NSString *)leftValue {
    // 检查缓存
    if (self.rightDataCache[leftValue]) {
        return;
    }
    
    // 设置加载标志
    self.isLoading = YES;
    
    // 优先使用 block 回调
    if (self.requestRightDataBlock) {
        self.requestRightDataBlock(leftValue, ^(NSArray *rightData) {
            [self loadRightDataForLeftValue:leftValue withData:rightData];
        });
        return;
    }
    
    // 其次使用代理
    if ([self.delegate respondsToSelector:@selector(cascadePickerView:requestRightDataForLeftValue:completion:)]) {
        [self.delegate cascadePickerView:self requestRightDataForLeftValue:leftValue completion:^(NSArray *rightData) {
            [self loadRightDataForLeftValue:leftValue withData:rightData];
        }];
        return;
    }
    
    // 如果都没有设置，则显示空数据
    [self loadRightDataForLeftValue:leftValue withData:@[]];
}

- (void)loadRightDataForLeftValue:(NSString *)leftValue withData:(NSArray *)rightData {
    // 存储到缓存
    self.rightDataCache[leftValue] = rightData;
    
    // 刷新 picker
    if (self.columns > 1) {
        [self.pickerView reloadComponent:1];
    }
    
    // 重置加载标志
    self.isLoading = NO;
}

@end
